package com.shawn.example.mvvmdemo.home.ui.home

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.Toast
import androidx.core.view.*
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import cn.bingoogolapple.bgabanner.BGABanner
import com.alibaba.android.arouter.facade.annotation.Route
import com.jetpack.mvvm.lib.base.BaseFragment
import com.jetpack.mvvm.lib.base.RouterConstant
import com.jetpack.mvvm.lib.binding.ext.viewBind
import com.jetpack.mvvm.lib.common.databinding.LayoutLoadingBinding
import com.jetpack.mvvm.lib.common.ext.observe
import com.jetpack.mvvm.lib.common.ext.observeState
import com.jetpack.mvvm.lib.common.modules.BaseStatus
import com.jetpack.mvvm.lib.common.utils.ImageLoader
import com.jetpack.mvvm.lib.common.widget.SpaceItemDecoration
import com.shawn.example.mvvmdemo.home.databinding.FragmentHomeBinding
import com.shawn.example.mvvmdemo.home.databinding.ItemHomeBannerBinding
import com.shawn.example.mvvmdemo.home.model.ArticleDetail
import com.shawn.example.mvvmdemo.home.model.Banner
import com.shawn.example.mvvmdemo.home.viewmodel.HomeViewModel
import dagger.hilt.android.AndroidEntryPoint

@Route(path = RouterConstant.Home.PAGE_HOME)
@AndroidEntryPoint
class HomeFragment : BaseFragment() {
    companion object {
        private const val TAG = "HomeFragment"
    }

    private val bind by viewBind<FragmentHomeBinding>()
    private val vm by viewModels<HomeViewModel>()
    private lateinit var loadingBinding: LayoutLoadingBinding
    private lateinit var bannerBinding: ItemHomeBannerBinding
    private val articleList = mutableListOf<ArticleDetail>()

    /**
     * is Refresh
     */
    private var isRefresh = false
    private val homeAdapter: HomeAdapter by lazy {
        HomeAdapter(articleList)
    }

    /**
     * RefreshListener
     */
    private val onRefreshListener = SwipeRefreshLayout.OnRefreshListener {
        isRefresh = true
        vm.getArticles(0)
    }

    private val bannerAdapter: BGABanner.Adapter<ImageView, String> by lazy {
        BGABanner.Adapter<ImageView, String> { bgaBanner, imageView, feedImageUrl, position ->
            activity?.let { ImageLoader.load(it, feedImageUrl, imageView) }
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        loadingBinding = LayoutLoadingBinding.bind(bind.root)
        bannerBinding = ItemHomeBannerBinding.inflate(inflater, container, false)
        return bind.root
    }

    override fun lazyLoad() {
        vm.getArticles()
        vm.getBanner()
    }

    override fun initView() {
//        ViewCompat.setOnApplyWindowInsetsListener(bind.root) { v, insets ->
//            val sysBarInsets = insets.getInsets(WindowInsetsCompat.Type.systemBars())
//            v.updatePadding(sysBarInsets.left, sysBarInsets.top, sysBarInsets.right, 0)
//            WindowInsetsCompat.CONSUMED
//        }
        bind.swipeRefreshLayout.run {
            setOnRefreshListener(onRefreshListener)
        }
        bind.recyclerView.run {
            layoutManager = LinearLayoutManager(activity)
            adapter = homeAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(SpaceItemDecoration(requireActivity()))
        }
        homeAdapter.run {
            addHeaderView(bannerBinding.root)
        }
        bind.btnRetry.setOnClickListener {
            lazyLoad()
        }
    }

    override fun observeViewModel() {
        observe(vm.bannerLV, ::handleBannerList)
        observe(vm.articleListLV, ::handleArticle)
        observeState(vm.loadingLV, BaseStatus::isLoading) {
            loadingBinding.progressBar.isVisible = it
            if (it) {
                bind.errorLayout.isVisible = false
            }
        }
        observeState(vm.loadingLV, BaseStatus::isError, true) {
            Toast.makeText(requireActivity(), "load error", Toast.LENGTH_SHORT).show()
            if (articleList.isEmpty()) {
                bind.errorLayout.isVisible = true
            }
        }
    }

    private fun handleBannerList(bannerList: List<Banner>) {
        val bannerFeedList = ArrayList<String>()
        val bannerTitleList = ArrayList<String>()
        bannerList.forEach { banner ->
            bannerFeedList.add(banner.imagePath)
            bannerTitleList.add(banner.title)
        }
        bannerBinding.banner.run {
            setAutoPlayAble(bannerFeedList.size > 1)
            setData(bannerFeedList, bannerTitleList)
            setAdapter(bannerAdapter)
        }
    }

    private fun handleArticle(articles: List<ArticleDetail>) {
        bind.swipeRefreshLayout.isRefreshing = false
        if (isRefresh) {
            articleList.clear()
            articleList.addAll(articles)
            homeAdapter.setList(articleList)
        } else {
            articleList.addAll(articles)
            homeAdapter.addData(articleList)
        }
    }
}